<template>
  <div>
    <div style="display: flex;height: 100%;">
      <base-layout title="组织机构" ref="organLayout" style="width: 240px;" :bottonShow="false" :isPage="false"
                   :operateButtonSwitch="false" :mainColor="mainColor"
      >
        <div slot="main" style="height: 100%;border-right: 1px solid #dfe6ec;overflow-y: auto;">
          <base-tree ref="baseTree" :isCenter="false" :isSaveBtn="false" :Allshow="false" :showCheckbox="false"
                     :menuData="menuData" @handleNodeClick="orangClick"
          ></base-tree>
        </div>
      </base-layout>
      <base-layout title="用户信息" ref="userLayout" :selectTable="selectTable" @pageChange="pageChange" style="flex:1"
                   :buttonList="buttonList" @onElSelect="getElSelect" @onFuncBtn="getFuncBtn" :isPage="true"
      >
        <div slot="main" slot-scope="{ tableHeight }" style="height: 100%;">
          <base-table ref="userCustomtable" :border="true" :showIndex="false" :tabLoading.sync="tabLoading"
                      @radioChange="userRadioChange" :slotrow="true" :tableHeight="tableHeight" :tableData="tableData"
                      :tableColumn="tableColumn"
          >
            <template #state="{row}">
              <div>{{ row.row.state == 0 ? '启动' : '停用' }}</div>
            </template>
          </base-table>
        </div>
      </base-layout>
    </div>
    <base-dialog :closeEscape="true" :showClose="true" :closeModal="false" :dialogVisible.sync="addDialog"
                 :footerShow="true" @handleConfirmClick="handleConfirmClick" class="userDialog"
                 :title="dialogType == 'add' ? '新增用户信息' : '编辑用户信息'" width="900px" top="8vh"
    >
      <base-form ref="customForm" :formRow="formRow" :isFunBtn="false" @elDialogClick="elDialogClick">
      </base-form>
      <div>
        <p class="bigTitle">选择公司</p>
        <div flex="cross:center" flex-wrap>
          <p v-for="(item, index) in companyList" :class="{ 'active': item.isActive }" :key="index"
             @click="item.isActive = !item.isActive" class="roleName"
          >{{ item.organName }}</p>
        </div>
      </div>
      <div>
        <p class="bigTitle">选择角色</p>
        <div flex="cross:center" flex-wrap>
          <p v-for="(item, index) in roleList" :class="{ 'active': item.isActive }" :key="index"
             @click="item.isActive = !item.isActive" class="roleName"
          >{{ item.roleName }}</p>
        </div>
      </div>
    </base-dialog>
    <!--选择人员 -->
    <base-person ref="basePerson" :menuData="menuData" :tableColumn="personColumn"
                 @personConfirmClick="personConfirmClick"
    ></base-person>
  </div>
</template>

<script>
import baseLayout from '@/components/base/baseLayout'
import baseTable from '@/components/base/baseTable'
// import baseDialog from "@/components/base/BaseNewDialog";
import baseDialog from '@/components/base/BaseNewDialog/index.vue'
import baseForm from '@/components/base/baseNewForm/index.vue'
import baseTree from '@/components/base/BaseMenuTree/index.vue'
import basePerson from '@/components/base/basePerson/index.vue'
import configData from './configData'
import { getCompanyId } from '@/utils/auth'

import {
  PersonDetail,
  PersonSaveData
} from '@/api/apis/personnelSettings'
import {
  RoleGetBillList
} from '@/api/apis/roleManagement'
import {
  userGetBillList,
  userGetBillData,
  userSaveData,
  userOpen,
  userClose,
  userResetPwd,
  userChangePwd
} from '@/api/apis/userInformation'
import {
  GetOrganTree,
  OrganGetCompany
} from '@/api/apis/organization'
import {
  PersonList
} from '@/api/apis/personnelSettings'
import { authApi } from '@/api/apis/auth'

export default {
  name: 'UserInformation',
  components: {
    baseLayout,
    baseTable,
    baseDialog,
    baseForm,
    baseTree,
    basePerson
  },
  data() {
    return {
      userRadioIndex: false,
      userRadioId: false,
      personHight: '350px', //人员选择高度
      personMainHight: 'calc(100% - 39px)', //人员弹框高度
      personLoading: false, //人员加载
      personDialog: false,
      personTableData: [],
      personTableHeight: '280px', //人员表格高度
      roleList: [],
      companyList: [],
      // tableHeight: 'calc(100vh - 227px)',
      mainColor: '#f8f8f8',
      tabLoading: false,
      tableData: [],
      selectTable: [],
      selectPerson: [],
      dialogType: '',
      // 搜索配置
      addDialog: false,
      roleOptions: configData.roleOptions,
      formRow: configData.formRow1,
      formRow2: configData.formRow2,
      isFunBtn: true,
      menuData: [],
      infoData: '',
      buttonList: [

        {
          'icon': 'el-icon-refresh',
          'menuName': '重置密码'
        },
        {
          'icon': 'el-icon-open',
          'menuName': '启用'
        },
        {
          'icon': 'el-icon-turn-off',
          'menuName': '停用',
          type: 'danger'
        }
      ],
      pageModel: {
        pageNum: 1,
        pageSize: 20,
        organId: ''
        // SequenceName:'',
        // Sequence:''
      },
      personModel: {
        page: 1,
        limit: 20,
        organId: ''
      }
    }
  },
  computed: {
    // 表头配置
    tableColumn() {
      return configData.tableColumnJson
    },
    // 表头配置
    personColumn() {
      return configData.personColumn
    }
  },
  watch: {
    // pageModel: {
    // 	deep: true, //深度监听设置为 true
    // 	handler: function(newV, oldV) {
    // 		this.getTableList()
    // 	}
    // },
    addDialog: {
      deep: true, //深度监听设置为 true
      handler: function(newV, oldV) {
        if (newV == false) {
          this.formRow[0].elCol[0].disabled = false
          this.$nextTick(() => {
            this.$refs.customForm.resetForm('ruleForm')

          })
          if (this.roleList.length > 0) {
            this.roleList.forEach(el => {
              el.isActive = false
            })
          }
          if (this.companyList.length > 0) {
            this.companyList.forEach(el => {
              el.isActive = false
            })
          }

        }
      }
    },
    personModel: {
      deep: true, //深度监听设置为 true
      handler: function(newV, oldV) {
        this.getPersonList()
      }
    }
  },
  created() {
  },
  onShow() {
  },
  mounted() {
    this.initPage()
    // this.$refs.baseTree.getMenuList()
  },
  filters: {},
  methods: {
    // 初始化页面
    initPage() {
      this.getTableList()
      this.getOrganList()
    },

    // 获取用户信息列表
    async getTableList() {
      this.tabLoading = true
      this.tableData = []
      let params = {
        ...this.pageModel
      }
      let res = await authApi('sysUserService', '', 'queryEntityPage', '', params)
      if (res.status == 200) {
        this.tableData = res.attribute.list
        // this.$nextTick(() => {
        this.$refs.userCustomtable.clearRadioIndex()
        this.$refs.userLayout.setPageTotal(res.attribute.total)
        // })
        this.tabLoading = false
      }
    },
    // 单选
    userRadioChange(val) {
      this.userRadioIndex = val.index
      this.userRadioId = val.id
    },
    // 获取组织列表
    async getOrganList() {
      let res = await authApi('sysOrganService', '', 'queryEntityTree', '', {
        state: 0
      })
      this.menuData = res.attribute
    },
    // 获取角色列表
    async getRoleList(dataList) {
      let params = {
        page: 1,
        limit: 50,
        Sequence: '',
        SequenceName: ''
      }
      let res = await authApi('sysRoleService', '', 'queryEntity', '', { enableState: '0' })
      if (res.status == 200) {
        console.log(res, 'res')
        res.attribute.forEach(el => {
          el.isActive = false
          if (dataList && dataList.length > 0) {
            dataList.forEach(item => {
              console.log(item.id,el.id,'id对比')
              if (item.roleId == el.id) {
                el.isActive = true
              }
            })
          }
        })
        this.roleList = res.attribute
      }
    },
    // 获取公司列表
    async getCompanyList(dataList) {
      let res = await authApi('sysOrganService', '', 'queryEntityTree', '', { state: 0 })
      if (res.status == 200) {
        console.log(res, '组织')
        res.attribute.forEach(el => {
          el.isActive = false
          if (dataList && dataList.length > 0) {
            dataList.forEach(item => {
              if (el.id == item.userCompanyId) {
                el.isActive = true
              }
            })
          }
        })
        this.companyList = res.attribute
      }
    },
    // 获得人员列表
    async getPersonList() {
      this.personLoading = true
      let params = {
        ...this.personModel
      }
      let res = await PersonList(params)
      if (res.code === 1) {
        this.personTableData = res.data[1]
        this.personLoading = false
      }
    },
    async userSave(params) {
      let res
      if(params.id){
        res = await authApi('sysUserService','','updateEntity','',params)

      }else{
        res = await authApi('sysUserService','','saveEntity','',params)
      }
      if (res.status == 200) {
        this.$vmNews('保存成功', 'success')
        this.resetTable()
        this.addDialog = false
      }
    },
    // 获得人员详情
    async getInfoData(id) {
      let params = {
        id: id
      }
      console.log(id)
      let res = await authApi('sysUserService','','getEntity','',params)
      this.infoData = res.attribute
      // this.infoData.p_PersonName = this.infoData.personName

      this.getRoleList(res.attribute.userRoles)
      this.getCompanyList(res.attribute.userCompanys)
      this.formRow[0].elCol[0].disabled = true
      this.addDialog = true
      this.$nextTick(() => {
        this.$refs.customForm.choiceAssignment(this.infoData)
      })

    },

    // 树状图点击
    personClick(data) {
      this.personModel.organId = data.id
    },
    elDialogClick() {
      this.$refs.basePerson.personDialog = true
      // this.personDialog = true
      this.getPersonList()
    },

    // 重置
    // result() {
    // 	this.selectTable = []
    // 	this.$refs.personCustomtable.clearSelect();
    // },
    // 树状图点击
    orangClick(data) {
      this.pageModel.organId = data.id
      this.resetTable()
      // this.result()
    },
    // 表格多选
    getPersonSelect(selectTable) {
      this.selectPerson = selectTable
    },
    async ResetPwd(id) {
      let params = {
        id: id
      }
      let res = await authApi('sysUserService','','resetPassword','',params)
      if (res.status == 200) {
        this.$vmNews('重置成功', 'success')
        this.resetTable()
        this.initPage()
      }
    },
    async openDelData(id) {
      let params = {
        id: id,
        state:0
      }
      let res = await authApi('sysUserService','','enableDisableEntity','',params)
      if (res.status == 200) {
        this.$vmNews('已成功启用', 'success')
        this.resetTable()
        this.initPage()
      }
    },
    async closeDelData(id) {
      let params = {
        id: id,
        state:1
      }
      let res = await authApi('sysUserService','','enableDisableEntity','',params)
      if (res.status == 200) {
        this.$vmNews('已成功停用', 'success')
        this.resetTable()
        this.initPage()
      }
    },
    resetTable() {
      this.pageModel.pageNum = 1
      this.userRadioId = false
      this.userRadioIndex = false
      this.selectTable = []
      this.$nextTick(() => {
        this.$refs.userCustomtable.clearSelect()
        this.$refs.userCustomtable.clearRadioIndex()
        this.$refs.userLayout.pageClear()
      })
      this.getTableList()
    },
    // 操作按钮事件
    getFuncBtn(btnEven) {
      if (btnEven.menuName === '新增') { // 新增
        this.dialogType = 'add'
        this.getRoleList()
        this.getCompanyList()
        this.addDialog = true
      }
      if (btnEven.menuName != '新增') {
        if (this.userRadioIndex === false) {
          this.$tipConfirm('请勾选需要处理的信息')
          return
        }
      }
      if (btnEven.menuName === '编辑') { // 编辑
        this.dialogType = 'edit'
        this.getInfoData(this.userRadioId)
        // this.$refs.customtable.clearSelect()
      }
      if (btnEven.menuName === '重置密码') { // 重置密码
        this.$confirm('确认重置密码吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.ResetPwd(this.userRadioId)
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消操作'
          })
        })
      }
      if (btnEven.menuName === '启用') { // 导入
        this.$confirm('确认启用吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.openDelData(this.userRadioId)
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消操作'
          })
        })
      }
      if (btnEven.menuName === '停用') { //
        this.$confirm('确认停用吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.closeDelData(this.userRadioId)
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消操作'
          })
        })
      }
      console.log(btnEven)
      if (btnEven.menuName === '删除') { // 删除
        // if (!this.judgeCheckbox()) {
        // 	return
        // }
        this.$confirm('确认删除吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.tableDelData(this.userRadioId)
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      }

    },
    // 删除功能
    async tableDelData(id) {
      let params = {
        id: id
      }
      let res = await authApi('sysUserService','','deleteEntity','',params)
      if (res.status == 200) {
        this.$vmNews('删除成功', 'success')
        this.resetTable()
        // this.pageModel.page = 1
        // this.$refs.personLayout.setPageNum(1)
      }
    },
    getElSelect(event, index, indexItem, param) {
    },
    handleConfirmClick() {
      let ruleForm = this.$refs.customForm.ruleForm
      let userCompanys = []
      let userRoles = []
      this.companyList.forEach(el => {
        if (el.isActive === true) {
          userCompanys.push({
            userCompanyId: el.id
          })
        }
      })
      this.roleList.forEach(el => {
        if (el.isActive == true) {
          userRoles.push({
            roleId: el.id
          })
        }
      })
      let params = {
        // U_UserID: this.dialogType == 'add' ? '00000000-0000-0000-0000-000000000000' : this.infoData.U_UserID,
        ...ruleForm,
        userCompanys: userCompanys,
        userRoles: userRoles
      }
      this.userSave(params)
    },
    personConfirmClick(val) {
      console.log(val)
      // P_PersonName 人员姓名  P_PersonCode工号  P_PersonID所属人员id   u_UserID用户id
      // u_UserID人员id  U_LoginCode账号=人员工号
      // this.$refs.customForm.ruleForm.U_PersonID = val.p_PersonID
      this.$refs.customForm.getField('personID', val.id)
      this.$refs.customForm.getField('loginCode', val.personCode)
      this.$refs.customForm.getField('personName', val.personName)
      this.$refs.basePerson.personDialog = false
    },
    pageChange(model) {
      this.pageModel.pageNum = model.page
      this.pageModel.pageSize = model.limit
      this.getTableList()
    }
  }
}
</script>
<style scoped lang="scss">
.roleName {
  padding: 10px 0;
  width: 90px;
  border: 2px solid #f2f2f2;
  background-color: #f2f2f2;
  margin: 0px 10px 10px 0px;
  text-align: center;
  cursor: pointer;
  box-shadow: 0 0 0 2px #f2f2f2;
  border-radius: 5px;
}

.active {
  background-color: #00a490;
  border: 2px solid #ffffff;
  color: white;
  box-shadow: 0 0 0 2px #00a490;
}

.bigTitle {
  padding-bottom: 10px;
  margin: 10px 0;
  font-size: 16px;
  font-weight: bold;
  border-bottom: 1px solid #ccc;
}

.organizationBody {
  display: flex;
  justify-content: space-evenly;
  background-color: #f2f3f4;
  padding: 10px
}
</style>
